<template>
  <div v-if="addAddressDialog">
    <el-dialog v-model="addAddressDialog" :title="title" width="35%" align-center>
      <el-form
        ref="ruleFormRef"
        label-width="120px"
        label-position="top"
        :model="addressForm"
        :rules="addressRules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址信息" prop="addressOptions">
              <el-cascader
                :options="regionData"
                v-model="addressForm.addressOptions"
                placeholder="请选择省市区"
                clearable
                @change="handleChange"
                style="width: 100%;"
              ></el-cascader>    
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="addressForm.address" clearable  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="邮编" prop="postalCode">
              <el-input v-model="addressForm.postalCode" clearable  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="addressForm.contact" clearable  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="收货人姓名" prop="receiver">
              <el-input v-model="addressForm.receiver" clearable  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址标签" prop="addressTags">
              <el-select
                v-model="addressForm.addressTags"
                multiple
                placeholder="请选择地址标签"
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="item in addressTagsData"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="默认地址" prop="isDefault">
              <el-switch v-model="addressForm.isDefault" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addAddressDialog = false">取消</el-button>
          <el-button type="primary" @click="addAddress">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref } from 'vue'
import { regionData, codeToText } from 'element-china-area-data'
import { _addAddress ,_editAddress } from '@/apis/address'
const addAddressDialog = ref(false)
const props = defineProps({
  addressForm:{
    type:Object,
    default:()=>{}
  }
})
const emit = defineEmits(['get-address'])
// 获取表单DOM
const ruleFormRef = ref(null) 
const title = ref('新增收货地址') 
// 添加地址数据对象
const addressForm = ref({
  id:'', //地址id
  addressOptions: [], //地址信息
  provinceCode:'', //省级编码
  cityCode:'', //市级/区编码
  countyCode:'', //地区编码
  address:'', //详细地址
  postalCode:'',//邮政编码
  receiver:'', //收货人姓名
  contact:'', //手机/电话
  addressTags:[], //地址标签
  isDefault: false, //是否为默认地址：0是、1否
  fullLocation:'', //收货人完整地址
})
// 地址规则对象
const addressRules = ref({
  addressOptions: [
    { required: true, message: '请选择省市区', trigger: 'blur' },
  ],
  address:[
    { required: true, message: '请填写详细地址', trigger: 'blur' },
  ],
  postalCode:[
    { required: true, message: '请填写邮编', trigger: 'blur' },
    { pattern: /^[\+\-]?\d*?\d*?$/, message: '只能输入数字' },
    { min: 6, max: 6, message: '长度为6个字符', trigger: 'change' }
  ],
  contact:[
    { required: true, message: '请填写联系方式', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请填写正确的联系方式' },
  ],
  receiver:[
    { required: true, message: '请填写收货人姓名', trigger: 'blur' },
  ],
  addressTags:[
    { required: true, message: '请至少选择一种地址标签', trigger: 'blur' },
  ]
})
// 重置新增地址按钮方法
const addNewAddress = () => {
  title.value = '新增收货地址'
  addAddressDialog.value = true,
  addressForm.value.id = '',
  addressForm.value.addressOptions = [],
  addressForm.value.receiver = '',
  addressForm.value.contact = '',
  addressForm.value.provinceCode = '',
  addressForm.value.cityCode = '',
  addressForm.value.countyCode = '',
  addressForm.value.address = '',
  addressForm.value.postalCode = '',
  addressForm.value.addressTags = [],
  addressForm.value.isDefault  = false,
  addressForm.value.fullLocation = ''
}
// 地址标签数据
const addressTagsData = ref(
  [
    {
      id:1,
      value: '家里',
      label: '家里',
    },
    {
      id:2,
      value: '学校',
      label: '学校',
    },
    {
      id:3,
      value: '公司',
      label: '公司',
    }
  ]
)
const handleChange = (val) => {
  addressForm.value.provinceCode = val[0]
  addressForm.value.cityCode = val[1]
  addressForm.value.countyCode = val[2]
  addressForm.value.fullLocation = codeToText[val[0]] + codeToText[val[1]] + codeToText[val[2]]
}
// 确定添加或者修改收货地址方法
const addAddress = () => {
  // 添加地址参数
  const addressParams = ref({
      id:addressForm.value.id,
      receiver: addressForm.value.receiver,
      contact: addressForm.value.contact,
      provinceCode: addressForm.value.provinceCode.length === 2 ? addressForm.value.provinceCode + '0000' : addressForm.value.provinceCode,
      cityCode: addressForm.value.cityCode.length === 4 ? addressForm.value.cityCode + '00' : addressForm.value.cityCode,
      countyCode: addressForm.value.countyCode,
      address: addressForm.value.address,
      postalCode: addressForm.value.postalCode || '111006',
      addressTags: addressForm.value.addressTags.join(','),
      isDefault: addressForm.value.isDefault === true ? 0 : 1,
      fullLocation: addressForm.value.fullLocation
  })
  ruleFormRef.value.validate( async (valid)=>{
    if (!valid) {
      return false
    }
    // TODO 请求接口
    if(title.value === '新增收货地址'){
      await _addAddress(addressParams.value)
      ElMessage.success('地址添加成功')
      addAddressDialog.value = false
      // 刷新地址数据
      emit('get-address')
    }else{
      await _editAddress(addressForm.value.id,addressParams.value)
      ElMessage.success('地址修改成功')
      addAddressDialog.value = false
      // 刷新地址数据
      emit('get-address')
    }
  })
}
// 修改地址方法
const editAddress = () => {
  title.value = '修改收货地址'
  addAddressDialog.value = true
  const provinceCode = props.addressForm.provinceCode.slice(0,2)
  const cityCode = props.addressForm.cityCode.slice(0,4)
  const countyCode = props.addressForm.countyCode
  addressForm.value = { ...props.addressForm }
  addressForm.value.addressOptions = [provinceCode, cityCode, countyCode]
  addressForm.value.isDefault = props.addressForm.isDefault === 0 ? true : false
  addressForm.value.addressTags = props.addressForm.addressTags.split(',')
}
// 暴露子组件属性、方法给父组件使用
defineExpose({
  addNewAddress,
  editAddress
})
</script>

<style lang="scss" scoped>

</style>